/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.gateway.config

import com.google.code.kaptcha.Constants
import com.google.code.kaptcha.impl.DefaultKaptcha
import com.google.code.kaptcha.util.Config
import java.util.Properties
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
 * 验证码配置
 * @author maoxiaodong
 */
@Configuration
@ConditionalOnClass(DefaultKaptcha::class)
@EnableConfigurationProperties(CaptchaProperties::class, KaptchaProperties::class)
class CaptchaConfig(val properties: KaptchaProperties) {

    /**
     * 创建验证码bean
     */
    @Bean
    fun defaultKaptcha(): DefaultKaptcha {
        val prop = Properties()

        prop.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, properties.width.toString())
        prop.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, properties.height.toString())

        val content = properties.content
        prop.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, content.source)
        prop.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, content.length.toString())
        prop.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE, content.space.toString())

        val backgroundColor = properties.backgroundColor
        prop.setProperty(Constants.KAPTCHA_BACKGROUND_CLR_FROM, backgroundColor.from)
        prop.setProperty(Constants.KAPTCHA_BACKGROUND_CLR_TO, backgroundColor.to)

        val border = properties.border
        prop.setProperty(Constants.KAPTCHA_BORDER, if (border.enabled) "yes" else "no")
        prop.setProperty(Constants.KAPTCHA_BORDER_COLOR, border.color)
        prop.setProperty(Constants.KAPTCHA_BORDER_THICKNESS, border.thickness.toString())

        val font = properties.font
        prop.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, font.name)
        prop.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, font.size.toString())
        prop.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, font.color)

        val defaultKaptcha = DefaultKaptcha()
        defaultKaptcha.config = Config(prop)
        return defaultKaptcha
    }

}
